// pages/ordinary/ordinary.js
const app = getApp()
const utils = require('../../utils/util.js');
const qiniu = require("../../utils/qiniu.min.js");
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imgid: '',
    imgpopup: false,
    imgCover: [],
    them: "",
    name: "",
    room: "",
    phone: '',
    startTime: utils.formatTime3(new Date(new Date().getTime() + 10000 * 60)).substring(0, 16),
    endTime: utils.formatTime3(new Date(new Date().getTime() + 3000 * 60 * 60)).substring(0, 16),
    address: "",
    guestGroup: [],
    isNull: false,
    imgArr: [],    //将图片展示页面
    organizationChecked: false,
    addOrg: [],
    addOrgFrom: [],
    blessings: '',
    autoFocus: false,
    showAddOrg: false,
    userInfo: '',
    actId: "",
    lockSave: false,
    isChoose: false,
    login: false,
    phone: false,
    loginShow: false,
    phoneshow: false,
    contents: [],
    description: '',
  },
  login() {
    if (this.data.login) {
      this.toggle('phoneshow', true)
      this.selectComponent('#phone').showClose()
    } else {
      this.toggle('loginShow', true)
      this.selectComponent('#login').showClose()
    }
  },
  toggleToast(e) {
    console.log(e.detail)
    if (!e.detail.loginShow) {
      this.toggle('loginShow', false)
    }
    this.onShow()
  },
  toggleToast1(e) {
    console.log(e.detail)
    if (!e.detail.phoneshow) {
      this.toggle('phoneshow', false)
    }
    this.onShow()
  },
  toggle(type, val) {
    this.setData({
      [type]: val
    });
  },
  imgpopup(e) {
    var that = this
    var type = e.currentTarget.dataset.type
    if (type == 0) {
      that.toggle('imgpopup', true);
    } else {
      that.toggle('imgpopup', false);
    }
    console.log('点击', that.data.imgpopup)
  },
  goedit() {
    wx.navigateTo({
      url: '/pages/edit/edit?id=' + this.data.actId + '&list=' + encodeURIComponent(JSON.stringify(this.data.contents))
    })
  },
  //更换封面图
  changeCover(e) {
    var that = this;
    var type = e.currentTarget.dataset.type
    if (type == 0) {
      wx.navigateTo({
        url: '/pages/gallery/gallery?type=' + 14 + '&id=' + that.data.imgid,
      })
    } else if (type == 1) {
      wx.chooseImage({
        count: 1,
        sizeType: ['original', 'compressed'],
        sourceType: ['camera'],
        success: function (res) {
          const filepath = res.tempFilePaths[0]
          const src = filepath
          wx.navigateTo({
            url: `/pages/cutFace/index?src=${src}`,
          })
        }
      })
    } else if (type == 2) {
      wx.chooseImage({
        count: 1,
        sizeType: ['original', 'compressed'],
        sourceType: ['album'],
        success: function (res) {
          const filepath = res.tempFilePaths[0]
          const src = filepath
          wx.navigateTo({
            url: `/pages/cutFace/index?src=${src}`,
          })
        }
      })
    }
  },

  setThem(e) {
    this.setData({
      them: e.detail.value.trim()
    })
  },
  peopleRoomInput(e) {
    this.setData({
      room: e.detail.value.trim()
    })
  },
  addressInput(e) {
    this.setData({
      address: e.detail.value.trim()
    })
  },
  //联系人姓名
  groupNameInput(e) {
    var index = e.currentTarget.dataset.index;
    var temp_str = 'guestGroup[' + index + '].name';
    this.setData({
      [temp_str]: e.detail.value.trim()
    })
  },
  groupPhoneInput(e) {
    var index = e.currentTarget.dataset.index;
    var temp_str = 'guestGroup[' + index + '].tel';
    this.setData({
      [temp_str]: e.detail.value.trim()
    })
  },
  onPickerChange(e) {
    this.setData({
      startTime: e.detail.dateString
    })
  },
  changeStartTime(e) {
    this.setData({
      startTime: e.detail.dateString,
      endTime: utils.formatTime3(new Date(new Date(e.detail.dateString.replace(/-/g, "/")).getTime() + 3000 * 60 * 60)).substring(0, 16),
      isChoose: true
    })
  },
  changeEndTime(e) {
    this.setData({
      endTime: e.detail.dateString,
    })
  },
  //获取授权
  judgeAuthorization(e) {
    console.log("打开地图")
    var that = this;
    wx.getSetting({
      success(res) {
        //首次调起授权
        if (res.authSetting['scope.userLocation']) {
          wx.showToast({
            title: '',
            icon: 'loading'
          });
          that.openMap()
        } else {
          //手动授权
          wx.authorize({
            scope: 'scope.userLocation',
            success() {
              wx.showToast({
                title: '',
                icon: 'loading'
              });
              that.openMap()
            },
            fail() {
              wx.showModal({
                title: '提示',
                content: '检测到您未授权一起来往获取您的位置信息，是否前往设置？',
                success(res) {
                  if (res.confirm) {
                    wx.openSetting({
                      complete(res) {
                        if (res.authSetting['scope.userLocation']) {
                          that.openMap();
                        }
                      },
                    })
                  }
                }
              })
            }
          })
        }
      },
    })
  },
  //调起地图组件
  openMap() {
    var that = this;
    wx.getLocation({
      type: 'gcj02',
      success(res) {
        wx.hideToast();
        var latitude = res.latitude
        var longitude = res.longitude
        wx.chooseLocation({
          latitude: latitude,
          longitude: longitude,
          scale: 14,
          success: function (res) {
            //获取地址信息
            that.setData({
              address: res.name,
            })
          },
        })
      },
      fail: function (res) {
        wx.hideToast();
        wx.showModal({
          title: '',
          content: '无法获取你的位置信息。请到手机系统的[设置]->[隐私]->[定位服务]中打开定位服务，并允许微信使用定位服务。',
          showCancel: false,
          confirmText: '确定',
          success: function (res) {
          }
        })
      }
    })
  },
  //增加联系人
  addGroup() {
    if (this.data.guestGroup.length < 3) {
      this.data.guestGroup.push({
        index: this.data.guestGroup.length + 1,
        name: "",
        tel: ""
      })
    }
    this.setData({
      guestGroup: this.data.guestGroup
    })
  },
  //移除联系人
  removeGroup(e) {
    this.removeAaary(this.data.guestGroup, e.currentTarget.dataset.item);
  },
  //移除数组
  removeAaary(_arr, _obj) {
    var length = _arr.length;
    for (var i = 0; i < length; i++) {
      if (_arr[i].index == _obj.index) {
        if (i == 0) {
          _arr.shift(); //删除并返回数组的第一个元素
          return this.setData({
            guestGroup: _arr
          });
        }
        else if (i == length - 1) {
          _arr.pop();  //删除并返回数组的最后一个元素
          return this.setData({
            guestGroup: _arr
          });
        }
        else {
          _arr.splice(i, 1); //删除下标为i的元素
          return this.setData({
            guestGroup: _arr
          });
        }
      }
    }
  },

  //活动概况图片
  posterimg() {
    var that = this;
    if (that.data.imgArr.length >= 3) {
      wx.showToast({
        title: '最多只能上传3张图片',
        icon: 'none',
        duration: 2000
      })
    } else {
      app.getQiNiuToken(function (res) {
        var countnum = 3 - that.data.imgArr.length
        var qiniuconfig = res;
        wx.chooseImage({
          count: countnum,
          sizeType: ['original', 'compressed'],
          sourceType: ['album', 'camera'],
          success: function (res) {
            const filepathArray = res.tempFilePaths
            for (let i = 0; i < filepathArray.length; i++) {
              qiniu.upload(filepathArray[i], res => {
                that.setData({
                  posterUrl: that.data.imgArr.concat([res.imageURL]),
                })
                that.toggle('imgArr', that.data.posterUrl)
              }, (error) => {
                // console.log('error' + error)
              }, {
                uploadURL: 'https://upload.qiniup.com',
                region: 'ECN',
                domain: qiniuconfig.qiniuDomain,
                uptoken: qiniuconfig.upToken,
              })
            }

          }
        })
      });
    }
  },
  delete: function (e) {
    var that = this;
    var index = e.currentTarget.dataset.index;
    that.remove(that.data.imgArr, that.data.imgArr[index]);
    that.setData({
      posterUrl: that.data.imgArr
    });
    that.toggle('imgArr', that.data.posterUrl);
  },
  //删除元素
  remove: function (array, val) {
    for (var i = 0; i < array.length; i++) {
      if (array[i] == val) {
        array.splice(i, 1);
      }
    }
  },

  peoplenameInput(e) {
    var that = this
    var peoplename = e.detail.value
    that.setData({
      name: peoplename
    })
  },
  phoneInput(e) {
    var that = this
    that.setData({
      phone: e.detail.value.trim()
    })
  },
  phoneblur(e) {
    var that = this
    that.setData({
      phone: e.detail.value
    })
    // if (that.data.phone.trim() != '' && (/^1[3465789]\d{9}$/.test(that.data.phone))) {
    // }
  },
  //输入祝福语
  blessingInput: function (e) {
    if (e.detail.value.trim().length == 0) {
      this.setData({
        blessings: ''
      })
    } else {
      this.setData({
        blessings: e.detail.value,
        blessingsxg: true,
      })
    }
  },
  changeSwitch(e) {
    this.setData({
      showAddOrg: e.detail.value
    })
  },
  //选择可见人员
  goOrg() {
    var member = [];
    for (var i in this.data.addOrg) {
      member.push(this.data.addOrg[i].id)
    }
    wx.navigateTo({
      url: '/pages/member/member?addOrg=' + JSON.stringify(member)
    })
  },
  save() {
    if (this.data.lockSave) {
      return
    }
    var that = this
    var phonePattern = /^((\d{3}-\d{8}|\d{4}-\d{7,8})|(1[3|4|5|6|7|8|9][0-9]{9}))$/;
    var startStamp = new Date(this.data.startTime.replace(/-/g, "/")).getTime();
    var endStamp = new Date(this.data.endTime.replace(/-/g, "/")).getTime();
    if (this.data.guestGroup.length != 0) {
      for (var i in this.data.guestGroup) {
        if (this.data.guestGroup[i].name == "" || this.data.guestGroup[i].tel == "" || !phonePattern.test(this.data.guestGroup[i].tel)) {
          this.setData({
            isNull: true
          })
        } else {
          this.setData({
            isNull: false
          })
        }
      }
    } else {
      this.setData({
        isNull: false
      })
    }
    if (that.data.them == '') {
      wx.showToast({
        title: '请输入活动主题',
        icon: 'none'
      })
      return;
    } else if (startStamp < new Date().getTime()) {
      wx.showToast({
        title: '活动开始时间要大于当前时间',
        icon: 'none',
        duration: 3000
      })
      return;
    } else if (startStamp >= endStamp) {
      wx.showToast({
        title: '活动结束时间要大于开始时间',
        icon: 'none',
        duration: 3000
      })
      return;
    } else if (that.data.startTime == '') {
      wx.showToast({
        title: '请输入开始时间',
        icon: 'none',
        duration: 3000
      })
      return;
    } else if (that.data.endTime == '') {
      wx.showToast({
        title: '请输入结束时间',
        icon: 'none'
      })
      return;
    } else if (this.data.isNull) {
      var text = "";
      for (var i in this.data.guestGroup) {
        if (this.data.guestGroup[i].name == "") {
          text = `请输入联系人${parseInt(i) + 1}姓名`;
          wx.showToast({
            title: text,
            icon: 'none'
          })
          return
        } else if (this.data.guestGroup[i].tel == "") {
          text = `请输入联系人${parseInt(i) + 1}手机号`;
          wx.showToast({
            title: text,
            icon: 'none'
          })
          return
        } else if (!phonePattern.test(this.data.guestGroup[i].tel)) {
          text = `联系人${parseInt(i) + 1}手机号格式有误`;
          wx.showToast({
            title: text,
            icon: 'none'
          })
          return
        }
      }
    } else if (this.data.contents.length <= 0) {
      this.setData({
        autoFocus: true
      })
      wx.showToast({
        title: '请输入寿宴祝福语，祝福一下寿星吧',
        icon: 'none'
      })
      return;
    } else if (this.data.showAddOrg && this.data.addOrg.length == 0) {
      wx.showToast({
        title: '请选择要展示的组织',
        icon: 'none'
      })
      return;
    } else {
      // wx.showModal({
      //   title: '',
      //   content: `请再次确认红包、礼物、礼金接收人姓名：${that.data.name}  手机号：${that.data.phone}`,
      //   showCancel:true,
      //   confirmText:"确认无误",
      //   cancelText:"返回修改",
      //   success(res) {
      //     if (res.confirm){
      this.setData({
        lockSave: true
      })
      if (that.data.actId) {
        console.log("更新")
        that.updateBirthdayParty();
      } else {
        that.addBirthdayParty();
      }
    }
  },
  getImgCover() {
    var uid = wx.getStorageSync('uid');
    if (uid == undefined || uid == '') {
      app.getUserInfo();
    } else {
      // app.req({
      //   url: "blessmini/blesscomment/imageList",
      //   data: {
      //     uid: uid,
      //     type:14
      //   },
      //   method:"post",
      //   success:((res) => {
      //     // console.log(res)
      //     this.setData({
      //       imgCover: [res.data[0].url]
      //     })
      //   })
      // }) 
      app.req({
        url: "wechat/activity/listByDictType",
        data: {
          dictType: "IS_OPEN_STATE",
          dictName: 14
        },
        method: "post",
        success: ((res) => {
          this.setData({
            imgCover: [res.data.headPicture],
            imgid: res.data.headPictureId
          })
        })
      })
    }
  },
  addBirthdayParty() {
    var that = this;
    var uid = wx.getStorageSync('uid');
    if (uid == undefined || uid == '') {
      app.getUserInfo();
    } else {
      app.req({
        url: "blessmini/blessold/addBlessOld?uid=" + uid,
        data: {
          babyName: that.data.them,
          organizerName: that.data.name,
          organizerMobile: that.data.phone,
          startTime: that.data.startTime + ":00",
          endTime: that.data.endTime + ":00",
          adress: that.data.address,
          room: that.data.room,
          pictureList: that.data.imgArr,
          topPictureList: that.data.imgCover,
          contactsList: that.data.guestGroup,
          description: that.data.description,
          orgList: that.data.addOrg,
          contents: that.data.contents,
          isOrgShow: that.data.showAddOrg ? 1 : 0
        },
        method: "post",
        success: function (res) {
          // console.log(res)
          if (res.code == 200) {
            that.setData({
              actId: res.data.actId
            })
            wx.showToast({
              title: that.data.showAddOrg ? "已提交组织审核" : "活动发布成功",
              icon: 'none',
              duration: 2000
            })
            setTimeout(() => {
              wx.redirectTo({
                // url: '/pages/register/register?id=' + res.data.id
                url: '/pages/hundredDetailed/hundredDetailed?id=' + res.data.actId + "&type=2"
              });
            }, 2000)
          } else {
            wx.showToast({
              title: res.msg,
              icon: 'none',
            })
          }
        },
        fail: function (err) {
          that.setData({
            lockSave: false,
          })
        }
      })
    }
  },
  updateBirthdayParty() {
    var that = this;
    var uid = wx.getStorageSync('uid');
    if (uid == undefined || uid == '') {
      app.getUserInfo();
    } else {
      app.req({
        url: "blessmini/blessold/updateBlessOld?uid=" + uid,
        data: {
          id: that.data.actId,
          babyName: that.data.them,
          organizerName: that.data.name,
          organizerMobile: that.data.phone,
          startTime: that.data.startTime + ":00",
          endTime: that.data.endTime + ":00",
          adress: that.data.address,
          room: that.data.room,
          pictureList: that.data.imgArr,
          topPictureList: that.data.imgCover,
          contactsList: that.data.guestGroup,
          description: that.data.description,
          contents: that.data.contents,
          orgList: that.data.showAddOrg ? that.data.addOrg : [],
          isOrgShow: that.data.showAddOrg ? 1 : 0
        },
        method: "post",
        success: function (res) {
          if (res.code == 200) {
            wx.showToast({
              title: that.data.showAddOrg ? "已提交组织审核" : "修改成功",
              icon: 'none',
              duration: 2000
            })
            setTimeout(() => {
              wx.redirectTo({
                // url: '/pages/register/register?id=' + res.data.id
                url: '/pages/hundredDetailed/hundredDetailed?id=' + res.data.actId + "&type=2"
              });
            }, 2000)
          } else {
            wx.showToast({
              title: res.msg,
              icon: 'none',
            })
          }
        },
        fail: function (err) {
          that.setData({
            lockSave: false,
          })
        }
      })
    }
  },
  //获取活动详情
  editBirthdayDay() {
    var that = this;
    var uid = wx.getStorageSync('uid');
    app.req({
      url: "blessmini/blesscommon/birthdayDetails",
      data: {
        uid: uid,
        id: that.data.actId, //生日ID
        // id: '203c7d2d021111ea945200163e05ff66', //生日ID
        actType: 2
      },
      method: "post",
      success: ((res) => {
        console.log("获取修改数据", res)
        if (res.code == 200) {
          that.setData({
            them: res.data.name,
            name: res.data.organizerName,
            phone: res.data.organizerMobile,
            imgCover: res.data.topPictureList,
            startTime: res.data.startTime.substring(0, 16),
            endTime: res.data.endTime.substring(0, 16),
            address: res.data.adress,
            room: res.data.room,
            imgArr: res.data.pictureList,
            blessings: res.data.description,
            guestGroup: res.data.contactsList,
            addOrg: res.data.exhibitionOrgList,
            showAddOrg: res.data.exhibitionOrgList.length != 0 ? true : false,
            organizationChecked: res.data.exhibitionOrgList.length != 0 ? true : false,
            actId: res.data.id,
            contents: res.data.contents
          })
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
          })
        }
      }),
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // var pages = getCurrentPages();
    // if (pages.length > 1 ){
    //   var prevPage = pages[pages.length - 2];
    //   if ( prevPage.route == "pages/index/index") {
    //     this.getImgCover();
    //   }
    // }
    //返回修改
    if (options.type == 1) {
      this.setData({
        actId: options.actId
      })
      wx.nextTick(() => {
        this.editBirthdayDay();
      })
    } //再次发起
    else if (options.type == 2) {

    } else {
      console.log("开发版")
      this.getImgCover();
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this
    if (wx.getStorageSync('uid') == '') {
      that.toggle("login", false);
      that.toggle('loginShow', true)
      console.log('隐藏2', that.data.loginShow)
    } else {
      that.toggle("login", true);
      console.log('隐藏3', that.data.phoneshow)
      var phone = wx.getStorageSync("phone")
      if (phone == '') {
        that.toggle("phone", true);
      } else {
        that.toggle("phone", false);
        that.toggle("phoneshow", false);
        that.toggle("loginShow", false);
        console.log('隐藏4', that.data.phoneshow)
        app.getUserInfo(function (userInfo) {
          that.setData({
            userInfo: userInfo,
            name: userInfo.realName,
            phone: userInfo.telphone,
            imgpopup: false
          })
        })
      }

    }

    if (!this.data.isChoose) {
      this.setData({
        startTime: utils.formatTime3(new Date(new Date().getTime() + 10000 * 60)).substring(0, 16),
        endTime: utils.formatTime3(new Date(new Date().getTime() + 3000 * 60 * 60)).substring(0, 16),
      })
    }
    // this.editBirthdayDay();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})